import os
import boto3

from lambda_helper.common_models import FilterList
from lambda_helper.dynamo_models import UserInfo

def is_running_on_aws_lambda():
    """检测是否在真正的AWS Lambda环境中运行"""
    # 方法1：检查Lambda特有的环境变量
    if 'AWS_LAMBDA_FUNCTION_NAME' in os.environ:
        return True
    
    # 方法2：检查Lambda执行路径环境变量
    if 'LAMBDA_TASK_ROOT' in os.environ:
        return True
    
    return False

def get_boto3_client(service_name):
    if not is_running_on_aws_lambda():
        access_key = os.environ.get('AWS_ACCESS_KEY_ID_LAMBDA')
        secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY_LAMBDA')
        region = os.environ.get('AWS_REGION_LAMBDA')
        boto3_client = boto3.client(
            service_name=service_name,
            aws_access_key_id=access_key,
            aws_secret_access_key=secret_key,
            region_name=region
        )
    else:
        boto3_client = boto3.client(service_name)
    return boto3_client

def get_boto3_resource(service_name):
    if not is_running_on_aws_lambda():
        access_key = os.environ.get('AWS_ACCESS_KEY_ID_LAMBDA')
        secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY_LAMBDA')
        region = os.environ.get('AWS_REGION_LAMBDA')
        boto3_resource = boto3.resource(
            service_name,
            aws_access_key_id=access_key,
            aws_secret_access_key=secret_key,
            region_name=region
        )
    else:
        boto3_resource = boto3.resource(service_name)
    return boto3_resource


class DynamoDB:
    def __init__(self, table_name: str):
        self.table_name = table_name
        self.dynamodb = get_boto3_resource('dynamodb')
        self.table = self.dynamodb.Table(self.table_name)

    def get_item_by_key(self, key: str, key_value: str) -> UserInfo:
        response = self.table.get_item(
            Key={
                key: key_value
            }
        )
        item = response.get('Item', {})
        if item:
            return UserInfo(**item)
        return None
    
    def get_items_by_scan(self, filter_expression: str, expression_values: dict) -> FilterList[UserInfo]:
        response = self.table.scan(
            FilterExpression=filter_expression,
            ExpressionAttributeValues=expression_values
        )
        items = response.get('Items', [])
        return FilterList(items)
    
    def put_item(self, item: dict) -> bool:
        response = self.table.put_item(
            Item=item
        )
        return response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200
    
    def delete_item(self, key: str, key_value: str) -> bool:
        response = self.table.delete_item(
            Key={
                key: key_value
            }
        )
        return response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200
    
    def update_item(self, key: str, key_value: str, update_expression: str, expression_values: dict) -> bool:
        response = self.table.update_item(
            Key={
                key: key_value
            },
            UpdateExpression=update_expression,
            ExpressionValues=expression_values
        )
        return response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200
    
class UserInfoDynamoDB(DynamoDB):
    def __init__(self):
        table_name = 'zhuchundashuaige_user'
        super().__init__(table_name)

    def get(self, user_id: str):
        response = self.get_item_by_key('user_id', user_id)
        return response
    
    def get_by_username(self, username: str):
        response = self.get_items_by_scan(
            filter_expression='username = :username',
            expression_values={
                ':username': username
            }
        )
        return response
    
    def get_by_platfrom(self, platfrom: str, platfrom_id: str):
        response = self.get_items_by_scan(
            filter_expression='platfrom = :platfrom AND platfrom_id = :platfrom_id',
            expression_values={
                ':platfrom': platfrom,
                ':platfrom_id': platfrom_id
            }
        )
        return response
    
